import Request from 'luch-request'
import { useUserStore } from '@/stores/user.js'

const tabBarList = [
	'pages/index/index',
	'pages/wiki/index',
	'pages/notify/index',
	'pages/my/index',
]

const whiteList = ['/code', '/login', '/login/password']

const http = new Request({
	baseURL: 'https://consult-api.itheima.net',
	custom: {
		loading: true,
	},
})

http.interceptors.request.use((config) => {
	if (config.custom.loading) {
		uni.showLoading({
			title: '正在加载...',
			mask: true,
		})
	}
	const userStore = useUserStore()
	const defaultHeader = {}
	if (userStore.token && !whiteList.includes(config.url)) {
		defaultHeader.Authorization = `Bearer ${userStore.token}`
	}
	config.header = {
		...defaultHeader,
		...config.header,
	}
	return config
})

http.interceptors.response.use(
	({ data, statusCode }) => {
		uni.hideLoading()
		return data
	},
	(error) => {
		uni.hideLoading()
		if (error.statusCode === 401) reLogin()
		return Promise.reject(error)
	}
)

const reLogin = () => {
	const pageStack = getCurrentPages()
	const currentPage = pageStack[pageStack.length - 1]
	const redirectURL = currentPage.$page.fullPath
	const openType = tabBarList.includes(currentPage.route)
		? 'switchTab'
		: 'redirectTo'
	const userStore = useUserStore()
	userStore.redirectURL = redirectURL
	userStore.openType = openType
	uni.redirectTo({
		url: '/pages/login/index',
	})
}

export { http }
